Regular Expression (Regex) is a search pattern, which can be used to find or replace certain text in strings.

Test Cases

Case 1 | Find

1
2
3
4
5
6
7
8
9
var testStringA = "This is a test string";
/* 'g' means global which means to return all matched text in the string */
/* 'i' means to ignore the case */
/* check if string contains 'test' */
var regexPatternA = /test/gi;
// output: 1
var textCountA = testStringA.match(regexPatternA).length;

Case 2 | Find

1
2
3
4
5
6
7
8
var testStringB = "This is a test string...";
/* '\' is used to ignore special character */
/* check if string contains '.' */
var regexPatternB = /\./gi;
// output: 3
var textCountB = testStringB.match(regexPatternB).length;

Case 3 | Find

1
2
3
4
5
6
7
8
9
10
11
12
var testStringC = "This is a test string with number 12345 ...";
/* '\d+', '\d' means to match digits, '+' means to match one or more digits */
/* check if string contains '.' */
var regexPatternC1 = /\d+/gi;
var regexPatternC2 = /\d/gi; // var regexPatternC2 = /[1-9]/gi;
// output: 1 | ['12345']
var textCountC1 = testStringC.match(regexPatternC1).length;
// output: 5 | ['1', '2', '3', '4', '5']
var textCountC2 = testStringC.match(regexPatternC2).length;

Case 4 | Replace

1
2
3
4
5
6
7
var testString = "This is a test string for function xxx ";
/* match text 'xxx' */
var regexPattern = /xxx/gi;
var newstring = testString.replace(regexPattern, 'Replace');
console.log(newstring); // This is a test string for function Replace

Case 5 | Test

1
2
3
4
5
6
7
8
9
10
// The Regex test() method will return true or false when match a certain string
var regexNumTest = /\d/g; // test if string contains digits
var regexStartTest = /^[A-Z]/g; // test if string start with any word from A-Z
var regexEndTest = /[0-9]$/g; // test if string end with any digits from 0-9
var testString = "This is a test string for function test";
regexNumTest.test(testString); // false
regexStartTest.test(testString); // true
regexEndTest.test(testString); // false

Resource

Regex Cheatsheet
MDN - Regualr Expressions
MDN - Regex Test
MDN - String.prototype.replace()

Comment and share

1. Usage of Unicode Character

“I hear and I forget. I see and I remember. I do and I understand.”

1
2
var rate = 3
"★★★★★☆☆☆☆☆".slice(5 - rate, 10 - rate);

2. An efficient way to handle JavaScript exception

1
2
3
4
5
6
7
8
// by 'Jordan Hall'
try {
//something
} catch (e) {
window.location.href =
"http://stackoverflow.com/search?q=[js]+" +
e.message;
}

3. Locate all DOM elements visually

1
2
3
4
5
6
7
8
// by 'Addy Osmani' https://addyosmani.com/
[].forEach.call($$("*"),function(a){
a.style.outline="1px solid #"+(~~(Math.random()*(1<<24))).toString(16)
})
Array.prototype.forEach.call(document.querySelectorAll('*'),
dom => dom.style.outline = `1px solid #${parseInt(Math.random() *
Math.pow(2,24)).toString(16)}`)

4. Separate number with ,

1
2
3
4
var test1 = '1234567890'
var format = test1.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
console.log(format) //Output: 1,234,567,890

5. An unofficial way to do deep clone for JSON object

1
2
3
4
5
var a = {
a: 1,
b: { c: 1, d: 2 }
}
var b=JSON.parse(JSON.stringify(a))

6. Implicitly convert string to number

1
2
var a =1
+a

7. Usage of ES6 Spread Operator

1
2
3
4
5
// quickly remove duplicated number
[...new Set([2, "2", 3, 3, 4, 1])] //output: [2, "2", 3, 4, 1]
// create an array with length 3 and all number 2
Array(3).fill(2) //outpput: [2, 2, 2]

8. Find Max and Min use Math

1
2
3
var numbers = [-99, 0 , 99 , 98 , -1];
var maxNum = Math.max.apply(Math, numbers); // output: 99
var minNum = Math.min.apply(Math, numbers); // ouput: -99

9. Debugging tips

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// eye candy for JSON view
var fruits = [
{ fruit: 'Tangerine', weight: 43 },
{ fruit: 'Cherry', weight: 13 },
{ fruit: 'Litchi', weight: 25 }
];
console.table(fruits);
// output code snippets execution time period
console.time('Timer01');
var items = [];
for(var i = 0; i < 100000; i++){
items.push({index: i});
}
console.timeEnd('Timer01');

10. Remove Timers from Global Scope

1
2
3
4
var highestTimeoutId = setTimeout(";");
for(var i=0; i<hightestTimeoutId; i++){
clearTimeout(i);
}

Comment and share

“The world and your career are unpredictable, so you are better off learning subjects of permanent value” - Gian-Carlo Rota

fetch() is a global method provided by Fetch API which can be used to GET or POST data asynchronously through the network.

GET

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
fetch("url", {
method: "GET",
mode: 'cors'
}
// default method is 'GET' if not provided
// add "mode: 'cors'" to send cross orign request
).then(
response => response.json()
// methed json() will convert the ReadableStream to json data format
).then(
data => console.log('Json data retrieved:', data)
// data is ready for use
);
// you can also use methods below to extract a body
// arrayBuffer(), blob(), text(), formData()

POST

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var dataToServer = {....};
fetch("url", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(dataToServer)
}
// set headers as needed
).then(
response => response.text()
// response from server
).then(
result => console.log('Result content:', result)
).catch(
err => console.log('error meesage', err.messge)
);

Difference between fetch() and jQuery.ajax()

From Fetch API:

The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.
By default, fetch won’t send or receive any cookies from the server, resulting in unauthenticated requests if the site relies on maintaining a user session (to send cookies, the credentials init option must be set).

Comment and share

Don’t Repeat Yourself

JavaScript has been developed rapidly in past few years. Developers are able to accumulate experience through reduplicated work. However, in order to improve the work efficiency and code quality, it is suggested to organize and maintain your codebase in a elegant way - Write your own JS Library.

How

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
(function(window){ /* function scope starts here */
'use strict';
function define_library(){
var LogDecorator = {}; // will be returned as a global variable
var logging = true; // disable/enable logging globally
var logPrefix = "----------------Start---------------------";
var logSuffix = "-----------------End---------------------";
LogDecorator.log = function(option, targetObj){
if(logging === true){
console.log(logPrefix);
console.log(`Option: ${option}`);
console.log('Target Object:');
console.log(targetObj);
console.log(logSuffix);
}
}
return LogDecorator;
}
//define globally if it doesn't already exist
if(typeof(LogDecorator) === 'undefined'){
window.LogDecorator = define_library();
}
else{
console.log("LogDecorator has already been defined.");
}
})(window); /* function scope ends */

Output Sample:

Test SampleTest Sample

Why

  1. Use Strict can eliminate silent errors by changing them to throw errors. Besides, Strict Mode can help JavaScript engines to perform optimizations. Refer to Strict mode for more details.

  2. Core Concept - JS Closures & Immediately-Invoked Function Expression

    Below is one way of using closures to define public functions that can access private functions and variables which is known as module pattern:

    1
    2
    3
    4
    5
    6
    (function() {
    // properties
    // methods
    // ...
    })(window);
    // Self-Executing Anonymous Functions

    () is the scope set for this function you are able to create private methods/functions and properties inside local scope. window inside () is used as global scope in browser environment.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    // closures example
    var globalVar = 0;
    (function outerFunc(outerArg) {
    var outerVar = 3;
    (function innerFunc(innerArg) {
    var innerVar = 4;
    console.log(
    "outerArg = " + outerArg + "\n" +
    "innerArg = " + innerArg + "\n" +
    "outerVar = " + outerVar + "\n" +
    "innerVar = " + innerVar + "\n" +
    "globalVar = " + globalVar);
    })(2);
    })(1);
    // output:
    // outerArg = 1
    // innerArg = 2
    // outerVar = 3
    // innerVar = 4
    // globalVar = 0

Comment and share

Diffie-Hellman Key Exchange (Value marked as red is private and only visible to its owner)Diffie-Hellman Key Exchange (Value marked as red is private and only visible to its owner)

Diffie-Hellman is a very simple algorithm which can be used to establish a shared secret between two parties.

How it works

Robot A use its private number a to generate value A and pass it to Robot B along with value g and p. Value g, p and A are all public. Robot B uses the same formula to generate value B using its private value b then transfers value B to Robot A. After all of that, Robot A and B can get same value R without exposing its private values to others.

Usage of D-H and Concept Behind

During the network communications, data can be eaily exposed to attackers. D-H provides a fantastic solution for that. Using D-H algorithm, users can estalish a secret even through public channels.

The key concept of this algorithm is Trapdoor Function which is widely used in cryptography. In this case, f(x)=g^x mod p is a Trapdoor Function, f(x) can be easily calculated when x is given but the computation of the inverse of f can hardly be done.

Comment and share

Observer pattern (also known as Pub/Sub pattern) can be used to help break down a whole application into more loosely coupled modules.

There would be an object (observer collection) maintains a list of events. Those observers (subscriber) will be automatically notified once the event occurs.

Code Sample:

  1. observer subscribes to an event by the event name. ‘globalBroadcaster’ is an observer collection which stores the events subscribed. ‘handler’ is the action observer will make once the event occurs.

    1
    globalBroadcaster.subscribe('uniqueEventName', handler);
  2. Once the event be published, all the subscribers of this event will be notified. parameters could be injected when event published and it can be used by the subscribers. */

    1
    globalBroadcaster.publish('uniqueEventName', parameter1, parameter2, ...);
  3. Observer can unsubsribe the event in the ‘handler’ after being notified. In this case, observer won’t be notified if same event published again.

    1
    globalBroadcaster.unsubscribe('uniqueEventName', handler);

Conclusion

The biggest benifit of using Sub/Pub pattern comes from the concept of decoupling. Observer A doesn’t need to worry about how the event published or who announces the event, ‘A’ will process its handler once be notified.

The disadvantages also come from decoupling modules. It would be hard for one to draw a clearly workflow since some of the actions processed on the fly. It will cause chaos if not implemented properly.

Anyhow, I like the concept of decoupling, especially in group work.

Comment and share

Author's picture

Zhao Cai

What will your verse be?


Web developer


Toronto